package com.yc.controller;


import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.yc.R_Code;
import com.yc.Result;
import com.yc.entities.*;
import com.yc.entities.custom.CustomOutPatientQueryRequestBean;
import com.yc.entities.custom.CustomRoleManageViewAndUpdatePullDownResponseBean;
import com.yc.entities.custom.CustomRoleQueryRequestBean;
import com.yc.entities.custom.CustomRoleSaveRequestBean;
import com.yc.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

/**
 * <p>
 * 角色表 前端控制器
 * </p>
 *
 * @author kuakha
 * @since 2021-04-07
 */
@RestController
@Slf4j
@RequestMapping("/bloodSugarRole")
@Api(value = "BloodSugarRoleController", tags = {"角色信息管理和出院患者"})
public class BloodSugarRoleController {

    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private BloodSugarRoleService bloodSugarRoleService;
    @Autowired
    private BloodSugarUserService bloodSugarUserService;
    @Autowired
    private BloodSugarUserRoleService bloodSugarUserRoleService;
    @Autowired
    private BloodSugarUserPermissionDepartmentService bloodSugarUserPermissionDepartmentService;
    @Autowired
    private BloodSugarDoctorService bloodSugarDoctorService;
    @Autowired
    private BloodSugarPatientInfoService bloodSugarPatientInfoService;
    @Autowired
    private BloodSugarPermissionService bloodSugarPermissionService;


    @ApiOperation(value = "pc添加角色信息")
    @PreAuthorize("hasAnyAuthority('sys:roleManage','sys:noAccess')")
    @PostMapping("addRole")
    @Transactional(rollbackFor = Exception.class)
    public Result addRole(@Valid @RequestBody CustomRoleSaveRequestBean customRoleSaveRequestBean) {
        LambdaQueryWrapper<BloodSugarUser> userLambdaQueryWrapper = Wrappers.lambdaQuery();
        userLambdaQueryWrapper.eq(BloodSugarUser::getAccount, customRoleSaveRequestBean.getAccount());
        List<BloodSugarUser> bloodSugarUsers = bloodSugarUserService.list(userLambdaQueryWrapper);

        if (bloodSugarUsers.size() == 0) {

            BloodSugarUser bloodSugarUser = new BloodSugarUser();
            bloodSugarUser.setAccount(customRoleSaveRequestBean.getAccount());
            bloodSugarUser.setPassword(passwordEncoder.encode(customRoleSaveRequestBean.getPassword()));
            int status = bloodSugarUserService.insert(bloodSugarUser);
            if (status >= 1) {
                BloodSugarDoctor bloodSugarDoctor = new BloodSugarDoctor();
                bloodSugarDoctor.setDoctorId(bloodSugarUser.getId());
                bloodSugarDoctor.setDeanId(customRoleSaveRequestBean.getDeanId());
                bloodSugarDoctor.setDoctorName(customRoleSaveRequestBean.getDoctorName());
                bloodSugarDoctor.setDepartmentId(customRoleSaveRequestBean.getDepartmentId());
                boolean save1 = bloodSugarDoctorService.save(bloodSugarDoctor);
                if (save1) {
                    BloodSugarUserRole bloodSugarUserRole = new BloodSugarUserRole();
                    bloodSugarUserRole.setUserId(bloodSugarUser.getId());
                    bloodSugarUserRole.setRoleId(customRoleSaveRequestBean.getRoleId());
                    boolean save = bloodSugarUserRoleService.save(bloodSugarUserRole);
                    if (save) {
                        Collection<BloodSugarUserPermissionDepartment> departmentCollections = new ArrayList<>();
                        customRoleSaveRequestBean.getAppLists().forEach((permissionId, departmentIds) -> {
                            departmentIds.forEach(departmentId -> {
                                LambdaQueryWrapper<BloodSugarPermission> lambdaQueryWrapper = Wrappers.lambdaQuery();
                                lambdaQueryWrapper.eq(BloodSugarPermission::getParentId, permissionId);
                                List<BloodSugarPermission> list = bloodSugarPermissionService.list(lambdaQueryWrapper);
                                departmentCollections.add(new BloodSugarUserPermissionDepartment()
                                        .setDepartmentId(Integer.parseInt(departmentId))
                                        .setPermissionId(Integer.parseInt(permissionId))
                                        .setUserId(bloodSugarUser.getId()));
                                list.forEach(f1 -> {
                                    departmentCollections.add(new BloodSugarUserPermissionDepartment()
                                            .setDepartmentId(Integer.parseInt(departmentId))
                                            .setPermissionId(f1.getId())
                                            .setUserId(bloodSugarUser.getId()));
                                });
                            });
                        });
                        customRoleSaveRequestBean.getPcLists().forEach((permissionId, departmentIds) -> {
                            departmentIds.forEach(departmentId -> {
                                LambdaQueryWrapper<BloodSugarPermission> lambdaQueryWrapper = Wrappers.lambdaQuery();
                                lambdaQueryWrapper.eq(BloodSugarPermission::getParentId, permissionId);
                                List<BloodSugarPermission> list = bloodSugarPermissionService.list(lambdaQueryWrapper);
                                departmentCollections.add(new BloodSugarUserPermissionDepartment()
                                        .setDepartmentId(Integer.parseInt(departmentId))
                                        .setPermissionId(Integer.parseInt(permissionId))
                                        .setUserId(bloodSugarUser.getId()));
                                list.forEach(f1 -> {
                                    departmentCollections.add(new BloodSugarUserPermissionDepartment()
                                            .setDepartmentId(Integer.parseInt(departmentId))
                                            .setPermissionId(f1.getId())
                                            .setUserId(bloodSugarUser.getId()));
                                });
                            });
                        });
                        boolean b1 = bloodSugarUserPermissionDepartmentService.saveBatch(departmentCollections);
                        if (b1) {
                            return Result.ok();
                        }
//                        }
                    }
                }
            }
            return Result.error().code(R_Code.R_ADD_FAIL);
        } else {
//            LambdaQueryWrapper<BloodSugarDoctor> doctorLambdaQueryWrapper = Wrappers.lambdaQuery();
//            doctorLambdaQueryWrapper.eq(BloodSugarDoctor::getDeanId, customRoleSaveRequestBean.getDeanId());
//            List<BloodSugarDoctor> doctorList = bloodSugarDoctorService.list(doctorLambdaQueryWrapper);
//            for (BloodSugarDoctor bloodSugarDoctor : doctorList) {
//                for (BloodSugarUser bloodSugarUser : bloodSugarUsers) {
//                    if (bloodSugarDoctor.getDoctorId().equals(bloodSugarUser.getId())) {
//                        return Result.error().message("此账号已存在");
//                    }
//                }
//            }
//            BloodSugarUser bloodSugarUser = new BloodSugarUser();
//            bloodSugarUser.setAccount(customRoleSaveRequestBean.getAccount());
//            bloodSugarUser.setPassword(passwordEncoder.encode(customRoleSaveRequestBean.getPassword()));
//            int status = bloodSugarUserService.insert(bloodSugarUser);
//            if (status >= 1) {
//                BloodSugarDoctor bloodSugarDoctor = new BloodSugarDoctor();
//                bloodSugarDoctor.setDoctorId(bloodSugarUser.getId());
//                bloodSugarDoctor.setDeanId(customRoleSaveRequestBean.getDeanId());
//                bloodSugarDoctor.setDoctorName(customRoleSaveRequestBean.getDoctorName());
//                bloodSugarDoctor.setDepartmentId(customRoleSaveRequestBean.getDepartmentId());
//                boolean save1 = bloodSugarDoctorService.save(bloodSugarDoctor);
//                if (save1) {
//                    BloodSugarUserRole bloodSugarUserRole = new BloodSugarUserRole();
//                    bloodSugarUserRole.setUserId(bloodSugarUser.getId());
//                    bloodSugarUserRole.setRoleId(customRoleSaveRequestBean.getRoleId());
//                    boolean save = bloodSugarUserRoleService.save(bloodSugarUserRole);
//                    if (save) {
//                        Collection<BloodSugarUserPermissionDepartment> departmentCollections = new ArrayList<>();
//                        customRoleSaveRequestBean.getAppLists().forEach((permissionId, departmentIds) -> {
//                            departmentIds.forEach(departmentId -> {
//                                LambdaQueryWrapper<BloodSugarPermission> lambdaQueryWrapper = Wrappers.lambdaQuery();
//                                lambdaQueryWrapper.eq(BloodSugarPermission::getParentId, permissionId);
//                                List<BloodSugarPermission> list = bloodSugarPermissionService.list(lambdaQueryWrapper);
//                                departmentCollections.add(new BloodSugarUserPermissionDepartment()
//                                        .setDepartmentId(Integer.parseInt(departmentId))
//                                        .setPermissionId(Integer.parseInt(permissionId))
//                                        .setUserId(bloodSugarUser.getId()));
//                                list.forEach(f1 -> {
//                                    departmentCollections.add(new BloodSugarUserPermissionDepartment()
//                                            .setDepartmentId(Integer.parseInt(departmentId))
//                                            .setPermissionId(f1.getId())
//                                            .setUserId(bloodSugarUser.getId()));
//                                });
//                            });
//                        });
//                        customRoleSaveRequestBean.getPcLists().forEach((permissionId, departmentIds) -> {
//                            departmentIds.forEach(departmentId -> {
//                                LambdaQueryWrapper<BloodSugarPermission> lambdaQueryWrapper = Wrappers.lambdaQuery();
//                                lambdaQueryWrapper.eq(BloodSugarPermission::getParentId, permissionId);
//                                List<BloodSugarPermission> list = bloodSugarPermissionService.list(lambdaQueryWrapper);
//                                departmentCollections.add(new BloodSugarUserPermissionDepartment()
//                                        .setDepartmentId(Integer.parseInt(departmentId))
//                                        .setPermissionId(Integer.parseInt(permissionId))
//                                        .setUserId(bloodSugarUser.getId()));
//                                list.forEach(f1 -> {
//                                    departmentCollections.add(new BloodSugarUserPermissionDepartment()
//                                            .setDepartmentId(Integer.parseInt(departmentId))
//                                            .setPermissionId(f1.getId())
//                                            .setUserId(bloodSugarUser.getId()));
//                                });
//                            });
//                        });
//                        boolean b1 = bloodSugarUserPermissionDepartmentService.saveBatch(departmentCollections);
//                        if (b1) {
//                            return Result.ok();
//                        }
//                    }
//                }
//                return Result.error().code(R_Code.R_ADD_FAIL);
//            }
            return Result.error().message("此账号已存在");
        }

    }


    @ApiOperation(value = "pc权限管理功能修改角色信息")
    @PreAuthorize("hasAnyAuthority('sys:roleManage','sys:noAccess')")
    @PostMapping("updateRole")
    @Transactional(rollbackFor = Exception.class)
    public Result updateRole(@Valid @RequestBody CustomRoleSaveRequestBean customRoleSaveRequestBean) {
        //设定查询条件（lamda表达式）
        LambdaQueryWrapper<BloodSugarUser> userLambdaQueryWrapper = Wrappers.lambdaQuery();
        userLambdaQueryWrapper.eq(BloodSugarUser::getAccount, customRoleSaveRequestBean.getAccount())
                .eq(BloodSugarUser::getId, customRoleSaveRequestBean.getId());
        //根据userID和account 确定唯一的用户
        BloodSugarUser one = bloodSugarUserService.getOne(userLambdaQueryWrapper);

        //非空判定
        if (one != null) {
            //单表修改
            BloodSugarUser bloodSugarUser = new BloodSugarUser();
            bloodSugarUser.setId(customRoleSaveRequestBean.getId());
            bloodSugarUser.setAccount(customRoleSaveRequestBean.getAccount());

            //MD5密码比对 相同为True
            if (one.getPassword().equals(customRoleSaveRequestBean.getPassword())) {
                bloodSugarUser.setPassword(one.getPassword());
            } else {
                bloodSugarUser.setPassword(passwordEncoder.encode(customRoleSaveRequestBean.getPassword()));
            }
            boolean status = bloodSugarUserService.updateById(bloodSugarUser);
            if (status) {
                BloodSugarDoctor bloodSugarDoctor = new BloodSugarDoctor();
                QueryWrapper<BloodSugarDoctor> queryWrapper = new QueryWrapper<>();
                QueryWrapper<BloodSugarDoctor> eqdocId = queryWrapper.eq("doctor_id", bloodSugarUser.getId());
                bloodSugarDoctor.setId(bloodSugarDoctorService.getOne(eqdocId).getId());
                bloodSugarDoctor.setDoctorId(bloodSugarUser.getId());
                bloodSugarDoctor.setDeanId(customRoleSaveRequestBean.getDeanId());
                bloodSugarDoctor.setDoctorName(customRoleSaveRequestBean.getDoctorName());
                bloodSugarDoctor.setDepartmentId(customRoleSaveRequestBean.getDepartmentId());
                boolean update1 = bloodSugarDoctorService.updateById(bloodSugarDoctor);
                if (update1) {
                    BloodSugarUserRole bloodSugarUserRole = new BloodSugarUserRole();
                    bloodSugarUserRole.setId(bloodSugarUser.getId());
                    bloodSugarUserRole.setUserId(bloodSugarUser.getId());

                    bloodSugarUserRole.setRoleId(customRoleSaveRequestBean.getRoleId() <= 1 ? 7 : customRoleSaveRequestBean.getRoleId());
                    boolean update2 = bloodSugarUserRoleService.updateById(bloodSugarUserRole);
                    if (update2) {
                        Collection<BloodSugarUserPermissionDepartment> departmentCollections = new ArrayList<>();
                        customRoleSaveRequestBean.getAppLists().forEach((permissionId, departmentIds) -> {
                            departmentIds.forEach(departmentId -> {
                                LambdaQueryWrapper<BloodSugarPermission> lambdaQueryWrapper = Wrappers.lambdaQuery();
                                lambdaQueryWrapper.eq(BloodSugarPermission::getParentId, permissionId);
                                List<BloodSugarPermission> list = bloodSugarPermissionService.list(lambdaQueryWrapper);
                                departmentCollections.add(new BloodSugarUserPermissionDepartment()
                                        .setDepartmentId(Integer.parseInt(departmentId))
                                        .setPermissionId(Integer.parseInt(permissionId))
                                        .setUserId(bloodSugarUser.getId()));
                                list.forEach(f1 -> {
                                    departmentCollections.add(new BloodSugarUserPermissionDepartment()
                                            .setDepartmentId(Integer.parseInt(departmentId))
                                            .setPermissionId(f1.getId())
                                            .setUserId(bloodSugarUser.getId()));
                                });
                            });
                        });
                        customRoleSaveRequestBean.getPcLists().forEach((permissionId, departmentIds) -> {
                            departmentIds.forEach(departmentId -> {
                                LambdaQueryWrapper<BloodSugarPermission> lambdaQueryWrapper = Wrappers.lambdaQuery();
                                lambdaQueryWrapper.eq(BloodSugarPermission::getParentId, permissionId);
                                List<BloodSugarPermission> list = bloodSugarPermissionService.list(lambdaQueryWrapper);
                                departmentCollections.add(new BloodSugarUserPermissionDepartment()
                                        .setDepartmentId(Integer.parseInt(departmentId))
                                        .setPermissionId(Integer.parseInt(permissionId))
                                        .setUserId(bloodSugarUser.getId()));
                                list.forEach(f1 -> {
                                    departmentCollections.add(new BloodSugarUserPermissionDepartment()
                                            .setDepartmentId(Integer.parseInt(departmentId))
                                            .setPermissionId(f1.getId())
                                            .setUserId(bloodSugarUser.getId()));
                                });
                            });
                        });
                        LambdaQueryWrapper<BloodSugarUserPermissionDepartment> lambdaQueryWrapper = Wrappers.lambdaQuery();
                        lambdaQueryWrapper.eq(BloodSugarUserPermissionDepartment::getUserId, bloodSugarUser.getId());
                        bloodSugarUserPermissionDepartmentService.remove(lambdaQueryWrapper);
                        boolean b1 = bloodSugarUserPermissionDepartmentService.saveBatch(departmentCollections);
                        if (b1) {
                            return Result.ok();
                        }
                    }
                }
            }
            return Result.error().code(R_Code.R_UPDATE_FAIL);
        } else {
            return Result.error().message("此账号不存在");
        }
    }

    @ApiOperation(value = "pc查询所有角色 角色管理添加修改角色信息下拉框使用")
    @PreAuthorize("hasAnyAuthority('sys:roleManage','sys:noAccess')")
    @PostMapping("getRoleInfo")
    public Result getRoleInfo() {
        LambdaQueryWrapper<BloodSugarRole> lambdaQueryWrapper = Wrappers.lambdaQuery();
        lambdaQueryWrapper.ne(BloodSugarRole::getRoleType, "0")
                .ne(BloodSugarRole::getRoleType, "1")
                .ne(BloodSugarRole::getRoleType, "6");
        List<BloodSugarRole> list = bloodSugarRoleService.list(lambdaQueryWrapper);
        if (list.size() > 0) {
            return Result.ok().data(list);
        } else {
            return Result.ok().code(R_Code.R_NULL_DATA_FAIL);
        }
    }

    @ApiOperation(value = "pc查询所有用户角色信息 角色管理列表的使用")
    @PreAuthorize("hasAnyAuthority('sys:roleManage','sys:noAccess')")
    @PostMapping(value = {"getAllRoleInfo"})
    public Result getAllRoleInfo(@Valid @RequestBody CustomRoleQueryRequestBean customRoleQueryRequestBean) {
        return bloodSugarRoleService.getAllRoleInfo(customRoleQueryRequestBean);
    }

    @ApiOperation(value = "pc权限管理功能查询角色信息")
    @PreAuthorize("hasAnyAuthority('sys:roleManage','sys:noAccess')")
    @GetMapping("getRole")
    public Result getRole(@RequestParam(value = "deanId") Integer deanId
            , @RequestParam(value = "userId") Integer userId) {
        return bloodSugarRoleService.getUserInfoByUserId(userId, deanId);
    }

    @ApiOperation(value = "删除角色信息(暂时没用)")
    @PreAuthorize("hasAnyAuthority('sys:roleManage','sys:noAccess')")
    @GetMapping("deleteRole")
    @Transactional(rollbackFor = Exception.class)
    public Result deleteRole() {
        return Result.ok();
    }

    @ApiOperation(value = "pc修改用户角色启用状态")
//    @PreAuthorize("hasAnyAuthority('sys:roleManage','sys:noAccess')")
    @GetMapping("updateUserRoleStatus/{userId}/{isDisable}")
    public Result updateUserRoleStatus(@ApiParam(name = "userId", value = "用户id") @NotNull(message = "用户id不能为空") @PathVariable Integer userId,
                                       @ApiParam(name = "isDisable", value = "账号启用状态 0:启用 1:禁用") @NotNull(message = "账号启用状态不能为空") @PathVariable String isDisable) {
        LambdaUpdateWrapper<BloodSugarUser> userWrapper = Wrappers.lambdaUpdate();
        userWrapper.eq(BloodSugarUser::getId, userId);
        userWrapper.set(BloodSugarUser::getIsDisable, isDisable);
        boolean update = bloodSugarUserService.update(userWrapper);
        if (update) {
            return Result.ok();
        } else {
            return Result.error().code(R_Code.R_UPDATE_FAIL);
        }
    }

    @ApiOperation(value = "pc查询所有出院患者信息")
    @PreAuthorize("hasAnyAuthority('sys:roleManage','sys:noAccess')")
    @PostMapping("getAllOutPatientInfo")
    public Result getAllOutPatientInfo(@Valid @RequestBody CustomOutPatientQueryRequestBean customOutPatientQueryRequestBean) {
        return bloodSugarPatientInfoService.getAllOutPatientInfo(customOutPatientQueryRequestBean);
    }


    @ApiOperation(value = "pc查询所有权限信息用于添加用户前渲染")
    @PreAuthorize("hasAnyAuthority('sys:roleManage','sys:noAccess')")
    @GetMapping("getAllPermissionToAdd")
    public Result getAllPermissionToAdd(@RequestParam Integer deanId) {
        return bloodSugarRoleService.getAllPermissionToAdd(null, deanId, deanId);
    }

}

